use std::time::Duration;
use crate::front::Front;
use crate::ir::IR;
use crate::parse::parse_round_bracket;

const SRC_CMD: &str = "SPI_WriteComm";
const SRC_DATA: &str = "SPI_WriteData";
const SRC_DELAY: &str = "Delay";

#[allow(non_camel_case_types)]
pub struct FPC4501MRYG_40C_MIPI{}

impl Front for FPC4501MRYG_40C_MIPI{
    fn parse(&self, src: &str) -> Vec<IR> {
        let mut out = vec![];
        let lines = src.
            split("\n")
            .filter(|s| s.contains(SRC_CMD)|| s.contains(SRC_DELAY));

        for line in lines {
            if line.contains("Delay") {

                let delay_str = parse_round_bracket(line);
                let ms = u64::from_str_radix(delay_str, 10).unwrap();
                out.push(IR::Delay(Duration::from_millis(ms)));
                continue;
            }

            let mut cmd= 0;
            let mut data = vec![];
            let elems = line.split(";");
            for elem in elems {
                if elem.contains(SRC_CMD) {
                    cmd = parse_round_bracket_hex_value(elem);
                }
                if elem.contains(SRC_DATA) {
                    data.push(parse_round_bracket_hex_value(elem));
                }
            }

            out.push(IR::Transfer{cmd, data});
        }

        out
    }
}

fn parse_round_bracket_hex_value(src: &str)->u8{
    let mut value_str = parse_round_bracket(src);
    value_str = value_str.trim_start_matches("0x");
    value_str = value_str.trim();
    u8::from_str_radix(value_str, 16).unwrap()
}